import React, { useEffect, useState } from "react";
import { Button, Form, Input, Select } from "antd";
import type { FormInstance } from "antd/es/form";
import { RoleType } from "@/types/user";
import { roleGet, userReg } from "@/api/user";

const layout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 16 },
};

const tailLayout = {
  wrapperCol: { offset: 8, span: 16 },
};

const UserForm: React.FC = () => {
  const formRef = React.useRef<FormInstance>(null);
  const [roleOptions, setRoleOptions] = useState<Array<RoleType>>();
  useEffect(() => {
    roleGet().then((res) => {
      setRoleOptions(res.data.results);
    });
  }, []);
  const onFinish = (values: any) => {
    console.log(values);
    userReg(values);
  };

  const onReset = () => {
    formRef.current?.resetFields();
  };

  return (
    <Form
      {...layout}
      ref={formRef}
      name="control-ref"
      onFinish={onFinish}
      style={{ maxWidth: 600 }}
    >
      <Form.Item name="username" label="账号" rules={[{ required: true }]}>
        <Input />
      </Form.Item>
      <Form.Item name="password" label="密码" rules={[{ required: true }]}>
        <Input type="password" />
      </Form.Item>
      <Form.Item label="角色" name="roleId" rules={[{ required: true }]}>
        <Select
          options={roleOptions}
          fieldNames={{ value: "objectId", label: "roleName" }}
        />
      </Form.Item>

      <Form.Item {...tailLayout}>
        <Button type="primary" htmlType="submit">
          确定
        </Button>
        <Button htmlType="button" onClick={onReset}>
          重置
        </Button>
      </Form.Item>
    </Form>
  );
};

export default UserForm;
